package gitee.blacol.myIdUtil.builder;

import gitee.blacol.myIdUtil.entity.ComplexId;
import gitee.blacol.myIdUtil.entity.IdBuilderConfig;
import gitee.blacol.myIdUtil.exception.MissingNecessaryParameters;

/**
 * 复杂ID构造器<br>
 * 需要指定参数才可以生成Id。<br>
 * 必须拥有的参数有：prefix、suffix、format
 */

public class ComplexIdBuilder extends IdBuilder<ComplexId> {
    //必选参数
    private String prefix;
    private String suffix;
    private String format;
    //可选参数
    private String[] pms={"prefix","suffix","format","file_path"};

    /**
     * 设置参数
     * @param config 适合复杂ID的参数Map
     * @return 复杂ID的Builder
     * @throws MissingNecessaryParameters 必选参数为null时抛出
     */

    @Override
    public IdBuilder<ComplexId> setConfig(IdBuilderConfig config) throws MissingNecessaryParameters {

        boolean key1=config.containsKey("prefix");
        boolean key2=config.containsKey("suffix");
        boolean key3=config.containsKey("format");
        boolean key4=config.containsKey("file_path");
        if (key1&&key2&&key3&&key4){
            String n_prefix = (String) config.get("prefix");
            String n_suffix = (String) config.get("suffix");
            String n_format = (String) config.get("format");
            if (config.containsKey("start_with_0")){
                startWith0=true;
            }
            if (config.containsKey("use_separator")){
                useSeparator=true;
            }
            if (config.containsKey("file_path")){
                filePath= (String) config.get("file_path");
            }
            prefix=n_prefix;
            suffix=n_suffix;
            format=n_format;
        }else{
            throw new MissingNecessaryParameters(pms);
        }
        return this;
    }

    /**
     * 根据配置生成ID
     * @return 生成的ID
     */
    @Override
    public ComplexId build(){
        ComplexId cId=new ComplexId();
        cId.setPrefix(prefix);
        cId.setSuffix(suffix);
        cId.setIndexFormat(format);
        if (startWith0){
            cId.setIndex(0);
        }
        if (useSeparator){
            String separator = (String) config.get("separator");
            cId.setSeparator(separator);
        }
        cId.setFilePath(filePath);
        return cId;
    }
}
